3 * Wrapper for object caching in different caches.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\ObjectFactory
;
26 * A cache class that replicates all writes to multiple child caches. Reads
27 * are implemented by reading from the caches in the order they are given in
28 * the configuration until a cache gives a positive result.
32 class MultiWriteBagOStuff
extends BagOStuff
{
33 /** @var BagOStuff[] */
35 /** @var bool Use async secondary writes */
36 protected $asyncWrites = false;
37 /** @var int[] List of all backing cache indexes */
38 protected $cacheIndexes = [];
40 const UPGRADE_TTL
= 3600; // TTL when a key is copied to a higher cache tier
44 * - caches: A numbered array of either ObjectFactory::getObjectFromSpec
45 * arrays yeilding BagOStuff objects or direct BagOStuff objects.
46 * If using the former, the 'args' field *must* be set.
47 * The first cache is the primary one, being the first to
48 * be read in the fallback chain. Writes happen to all stores
49 * in the order they are defined. However, lock()/unlock() calls
50 * only use the primary store.
51 * - replication: Either 'sync' or 'async'. This controls whether writes
52 * to secondary stores are deferred when possible. Async writes
53 * require setting 'asyncHandler'. HHVM register_postsend_function() function.
54 * Async writes can increase the chance of some race conditions
55 * or cause keys to expire seconds later than expected. It is
56 * safe to use for modules when cached values: are immutable,
57 * invalidation uses logical TTLs, invalidation uses etag/timestamp
58 * validation against the DB, or merge() is used to handle races.
59 * @param array $params
60 * @throws InvalidArgumentException
62 public function __construct( $params ) {
63 parent
::__construct( $params );
65 if ( empty( $params['caches'] ) ||
!is_array( $params['caches'] ) ) {
66 throw new InvalidArgumentException(
67 __METHOD__
. ': "caches" parameter must be an array of caches'
72 foreach ( $params['caches'] as $cacheInfo ) {
73 if ( $cacheInfo instanceof BagOStuff
) {
74 $this->caches
[] = $cacheInfo;
76 if ( !isset( $cacheInfo['args'] ) ) {
77 // B/C for when $cacheInfo was for ObjectCache::newFromParams().
78 // Callers intenting this to be for ObjectFactory::getObjectFromSpec
79 // should have set "args" per the docs above. Doings so avoids extra
80 // (likely harmless) params (factory/class/calls) ending up in "args".
81 $cacheInfo['args'] = [ $cacheInfo ];
83 $this->caches
[] = ObjectFactory
::getObjectFromSpec( $cacheInfo );
86 $this->mergeFlagMaps( $this->caches
);
88 $this->asyncWrites
= (
89 isset( $params['replication'] ) &&
90 $params['replication'] === 'async' &&
91 is_callable( $this->asyncHandler
)
94 $this->cacheIndexes
= array_keys( $this->caches
);
97 public function setDebug( $debug ) {
98 foreach ( $this->caches
as $cache ) {
99 $cache->setDebug( $debug );
103 protected function doGet( $key, $flags = 0 ) {
104 if ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
) {
105 // If the latest write was a delete(), we do NOT want to fallback
106 // to the other tiers and possibly see the old value. Also, this
107 // is used by merge(), which only needs to hit the primary.
108 return $this->caches
[0]->get( $key, $flags );
112 $missIndexes = []; // backends checked
113 foreach ( $this->caches
as $i => $cache ) {
114 $value = $cache->get( $key, $flags );
115 if ( $value !== false ) {
121 if ( $value !== false
123 && ( $flags & self
::READ_VERIFIED
) == self
::READ_VERIFIED
125 // Backfill the value to the higher (and often faster/smaller) cache tiers
127 $missIndexes, $this->asyncWrites
, 'set', $key, $value, self
::UPGRADE_TTL
134 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
135 $asyncWrites = ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
)
137 : $this->asyncWrites
;
139 return $this->doWrite( $this->cacheIndexes
, $asyncWrites, 'set', $key, $value, $exptime );
142 public function delete( $key, $flags = 0 ) {
143 return $this->doWrite( $this->cacheIndexes
, $this->asyncWrites
, 'delete', $key );
146 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
147 // Try the write to the top-tier cache
148 $ok = $this->doWrite( [ 0 ], $this->asyncWrites
, 'add', $key, $value, $exptime );
150 // Relay the add() using set() if it succeeded. This is meant to handle certain
151 // migration scenarios where the same store might get written to twice for certain
152 // keys. In that case, it does not make sense to return false due to "self-conflicts".
153 return $this->doWrite(
154 array_slice( $this->cacheIndexes
, 1 ),
166 public function incr( $key, $value = 1 ) {
167 return $this->doWrite( $this->cacheIndexes
, $this->asyncWrites
, 'incr', $key, $value );
170 public function decr( $key, $value = 1 ) {
171 return $this->doWrite( $this->cacheIndexes
, $this->asyncWrites
, 'decr', $key, $value );
174 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
175 $asyncWrites = ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
)
177 : $this->asyncWrites
;
179 return $this->doWrite(
191 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
192 // Only need to lock the first cache; also avoids deadlocks
193 return $this->caches
[0]->lock( $key, $timeout, $expiry, $rclass );
196 public function unlock( $key ) {
197 // Only the first cache is locked
198 return $this->caches
[0]->unlock( $key );
201 public function getLastError() {
202 return $this->caches
[0]->getLastError();
205 public function clearLastError() {
206 $this->caches
[0]->clearLastError();
210 * Apply a write method to the backing caches specified by $indexes (in order)
212 * @param int[] $indexes List of backing cache indexes
213 * @param bool $asyncWrites
214 * @param string $method
215 * @param mixed $args,...
218 protected function doWrite( $indexes, $asyncWrites, $method /*, ... */ ) {
220 $args = array_slice( func_get_args(), 3 );
222 if ( array_diff( $indexes, [ 0 ] ) && $asyncWrites && $method !== 'merge' ) {
223 // Deep-clone $args to prevent misbehavior when something writes an
224 // object to the BagOStuff then modifies it afterwards, e.g. T168040.
225 $args = unserialize( serialize( $args ) );
228 foreach ( $indexes as $i ) {
229 $cache = $this->caches
[$i];
230 if ( $i == 0 ||
!$asyncWrites ) {
231 // First store or in sync mode: write now and get result
232 if ( !$cache->$method( ...$args ) ) {
236 // Secondary write in async mode: do not block this HTTP request
237 $logger = $this->logger
;
238 ( $this->asyncHandler
)(
239 function () use ( $cache, $method, $args, $logger ) {
240 if ( !$cache->$method( ...$args ) ) {
241 $logger->warning( "Async $method op failed" );
252 * Delete objects expiring before a certain date.
254 * Succeed if any of the child caches succeed.
255 * @param string $date
256 * @param bool|callable $progressCallback
259 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
261 foreach ( $this->caches
as $cache ) {
262 if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
270 public function makeKeyInternal( $keyspace, $args ) {
271 return $this->caches
[0]->makeKeyInternal( ...func_get_args() );
274 public function makeKey( $class, $component = null ) {
275 return $this->caches
[0]->makeKey( ...func_get_args() );
278 public function makeGlobalKey( $class, $component = null ) {
279 return $this->caches
[0]->makeGlobalKey( ...func_get_args() );